import { reqUserLogin, reqUserOut } from '../../api/index';

const state = {
    userInfo: {
        name: localStorage.getItem('name'),
        token: localStorage.getItem('token'),
    },
};

const actions = {
    async getUserLogin({ commit }, user) {
        const result = await reqUserLogin(user);
        if (result.code === 200) {
            commit('SAVE_USER_LOGIN', result.data);
            //储存在localStorage中一份
            localStorage.setItem('name', result.data.name);
            localStorage.setItem('token', result.data.token);
            //这里要指定函数的返回值
            return result
        } else {
            console.log(result.message);
        }
    },
    async getUserOut({ commit }) {
        const result = await reqUserOut();
        if (result.code === 200) {
            localStorage.removeItem('name');
            localStorage.removeItem('token');
            commit('SAVE_USER_OUT', result.data);
        } else {
            console.log(result.message);
        }
    },
};

const mutations = {
    SAVE_USER_LOGIN(state, list) {
        state.userInfo.name = list.name;
        state.userInfo.token = list.token;
    },
    SAVE_USER_OUT(state) {
        state.userInfo.name = '';
        state.userInfo.token = '';
    },
};

export default {
    namespaced: true,
    state,
    actions,
    mutations,
};
